import 'package:flutter/foundation.dart';
import 'package:sqflite/sqflite.dart';
import '../models/mood.dart';
import '../models/database_helper.dart';
import '../utils/date_util.dart';
import 'package:intl/intl.dart';

class MoodProvider with ChangeNotifier {
  final DatabaseHelper _dbHelper = DatabaseHelper.instance;
  Mood? _currentMood;
  List<Mood> _moodHistory = [];
  bool _isLoading = false;
  List<Mood> _moods = [];

  // 获取当前情绪
  Mood? get currentMood => _currentMood;
  
  // 获取情绪历史
  List<Mood> get moodHistory => _moodHistory;
  
  // 加载状态
  bool get isLoading => _isLoading;

  List<Mood> get moods => _moods;

  // 初始化，加载今天的情绪记录
  Future<void> init() async {
    _isLoading = true;
    notifyListeners();

    try {
      // 初始化数据库连接
      await _dbHelper.database;
      // 加载所有情绪记录
      await loadMoods();
      // 加载今天的情绪记录
      await loadTodayMood();
    } catch (e) {
      debugPrint('初始化数据库失败: $e');
      _currentMood = null;
      _moods = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 加载今天的情绪记录
  Future<void> loadTodayMood() async {
    _isLoading = true;
    notifyListeners();

    try {
      final today = DateUtil.getCurrentDate();
      final moods = await _dbHelper.getMoods();
      try {
        _currentMood = moods.firstWhere((mood) => mood.date == today);
      } catch (e) {
        _currentMood = null;
      }
    } catch (e) {
      debugPrint('加载今日情绪失败: $e');
      _currentMood = null;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 保存情绪记录
  Future<bool> saveMood({
    required int moodType,
    required int intensity,
    required List<String> emotions,
    required List<String> triggers,
    required List<String> bodyReactions,
    required String description,
    String? imagePath,
  }) async {
    _isLoading = true;
    notifyListeners();

    try {
      final now = DateTime.now();
      final date = DateFormat('yyyy-MM-dd').format(now);
      final mood = Mood(
        id: DateTime.now().millisecondsSinceEpoch, // 使用时间戳作为临时 ID
        moodType: moodType,
        intensity: intensity,
        emotions: emotions,
        triggers: triggers,
        bodyReactions: bodyReactions,
        description: description,
        imagePath: imagePath,
        createdAt: now,
        date: date,
      );

      // 直接插入新记录
      final id = await _dbHelper.insertMood(mood);
      if (id != null) {
        // 重新加载所有情绪记录
        await loadMoods();
        // 重新加载今天的情绪记录
        await loadTodayMood();
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('保存情绪失败: $e');
      return false;
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 加载情绪历史记录
  Future<void> loadMoodHistory({String? startDate, String? endDate}) async {
    _isLoading = true;
    notifyListeners();

    try {
      final start = startDate ?? DateUtil.getOneMonthAgo();
      final end = endDate ?? DateUtil.getCurrentDate();
      
      final moods = await _dbHelper.getMoods();
      _moodHistory = moods.where((mood) => 
        mood.date.compareTo(start) >= 0 && mood.date.compareTo(end) <= 0
      ).toList();
    } catch (e) {
      debugPrint('加载情绪历史失败: $e');
      _moodHistory = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 获取情绪统计数据
  Future<Map<int, int>> getMoodStats({String? startDate, String? endDate}) async {
    try {
      final start = startDate ?? DateUtil.getOneMonthAgo();
      final end = endDate ?? DateUtil.getCurrentDate();
      
      final moods = await _dbHelper.getMoods();
      final filteredMoods = moods.where((mood) => 
        mood.date.compareTo(start) >= 0 && mood.date.compareTo(end) <= 0
      ).toList();
      
      final stats = <int, int>{};
      for (var mood in filteredMoods) {
        stats[mood.moodType] = (stats[mood.moodType] ?? 0) + 1;
      }
      return stats;
    } catch (e) {
      debugPrint('获取情绪统计失败: $e');
      return {};
    }
  }

  Future<List<Mood>> getAllMoods() async {
    _isLoading = true;
    notifyListeners();

    try {
      _moodHistory = await _dbHelper.getMoods();
      return _moodHistory;
    } catch (e) {
      debugPrint('Error getting moods: $e');
      return [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<List<Mood>> getMoodsByDate(String date) async {
    try {
      final moods = await _dbHelper.getMoods();
      return moods.where((mood) => mood.date == date).toList();
    } catch (e) {
      debugPrint('Error getting moods by date: $e');
      return [];
    }
  }

  Future<bool> deleteMood(int id) async {
    try {
      final success = await _dbHelper.deleteMood(id);
      if (success) {
        await loadMoods();
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('Error deleting mood: $e');
      return false;
    }
  }

  void clearCurrentMood() {
    _currentMood = null;
    notifyListeners();
  }

  Future<void> loadMoods() async {
    try {
      _moods = await _dbHelper.getMoods();
      notifyListeners();
    } catch (e) {
      debugPrint('加载情绪记录失败: $e');
      _moods = [];
      notifyListeners();
    }
  }
} 